package com.lineage.server.Instance.character;

import com.lineage.DatabaseFactory;
import com.lineage.server.model.Instance.L1PcInstance;
import com.lineage.server.utils.L1QueryUtil;
import com.lineage.server.utils.SQLUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class CharacterPunishInstance {
  private static final Log log = LogFactory.getLog(CharacterPunishInstance.class);
  
  private static final Map<Integer, String> punishList = new ConcurrentHashMap<>();
  
  private static CharacterPunishInstance instance;
  
  public CharacterPunishInstance() {
    load();
  }
  
  public static CharacterPunishInstance get() {
    if (instance == null)
      instance = new CharacterPunishInstance(); 
    return instance;
  }
  
  public void reload() {
    punishList.clear();
    load();
  }
  
  public void load() {
    Connection co = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
      co = DatabaseFactory.get().getConnection();
      ps = co.prepareStatement("SELECT * FROM `character_punish`");
      rs = ps.executeQuery();
      while (rs.next())
        punishList.put(Integer.valueOf(rs.getInt("chart_id")), rs.getString("char_name")); 
    } catch (SQLException e) {
      log.error(e.getLocalizedMessage(), e);
    } finally {
      SQLUtil.close(rs);
      SQLUtil.close(ps);
      SQLUtil.close(co);
    } 
    log.info("载入玩家惩罚名单:" + punishList.size());
  }
  
  public void addCharacter(L1PcInstance pc) {
    addCharacterToDb(Integer.valueOf(pc.getId()), pc.getName());
    punishList.put(Integer.valueOf(pc.getId()), pc.getName());
  }
  
  public void addCharacterToDb(Integer chartId, String chartName) {
    String sql = "INSERT INTO character_punish (chart_id, char_name) VALUE (?, ?)";
    L1QueryUtil.execute("INSERT INTO character_punish (chart_id, char_name) VALUE (?, ?)", new Object[] { chartId, chartName });
  }
  
  public void removeCharacter(L1PcInstance pc) {
    removeCharacter(Integer.valueOf(pc.getId()));
    punishList.remove(Integer.valueOf(pc.getId()));
  }
  
  public void removeCharacter(Integer chartId) {
    String sql = "DELETE FROM `character_punish` WHERE `chart_id`=?";
    L1QueryUtil.execute("DELETE FROM `character_punish` WHERE `chart_id`=?", new Object[] { chartId });
  }
  
  public Boolean checkCharacter(Integer chartId) {
    return Boolean.valueOf(punishList.containsKey(chartId));
  }
}
